package com.permission.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.permission.beans.LogType;
import com.permission.common.RequestHolder;
import com.permission.dao.SysLogMapper;
import com.permission.dao.SysRoleUserMapper;
import com.permission.dao.SysUserMapper;
import com.permission.entity.SysLogWithBLOBs;
import com.permission.entity.SysUser;
import com.permission.entity.SysUserRole;
import com.permission.service.SysLogService;
import com.permission.service.SysRoleUserService;
import com.permission.util.IpUtil;
import com.permission.util.JsonMapper;

@Service
public class SysRoleUserServiceImpl implements SysRoleUserService{

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysLogMapper sysLogMapper;
    /*
     * 这里为什么使用SysLogMapper而不使用SysLogService
     * 因为我们在SysLogService里面引用了“我本身”
     * 如果我们在这里再引用SysLogService就会形成循环
     */

    /**
     * 根据角色ID获取用户集合
     */
    public List<SysUser> getListByRoleId(int roleId) {
        //根据角色ID获取用户ID集合
        List<Integer> userIdList = sysRoleUserMapper.getUserIdListByRoleId(roleId);
        if (CollectionUtils.isEmpty(userIdList)) {
            return Lists.newArrayList();
        }
        //根据用户ID集合获取用户集合
        return sysUserMapper.getByIdList(userIdList);
    }


    /**
     * 修改角色拥有的用户
     */
    public void changeRoleUsers(int roleId, List<Integer> userIdList) {
        //1.获取该角色之前拥有的所有用户
        List<Integer> originUserIdList = sysRoleUserMapper.getUserIdListByRoleId(roleId);
        //2.判断用户ID和传进来的ID集合是否一致，一致的话则不执行修改
        if (originUserIdList.size() == userIdList.size()) {
            Set<Integer> originUserIdSet = Sets.newHashSet(originUserIdList);
            Set<Integer> userIdSet = Sets.newHashSet(userIdList);
            originUserIdSet.removeAll(userIdSet);
            if (CollectionUtils.isEmpty(originUserIdSet)) {
                return;
            }
        }
        //根据角色ID执行批量修改
        updateRoleUsers(roleId, userIdList);
        
        saveRoleUserLog(roleId, originUserIdList, userIdList);
    }

    /**
     * 根据角色ID执行批量修改
     */
    @Transactional
    private void updateRoleUsers(int roleId, List<Integer> userIdList) {
        //1.首先删除原来所有的用户
        sysRoleUserMapper.deleteByRoleId(roleId);
        //2.判断，如果用户ID集合是空的话就不执行添加
        if (CollectionUtils.isEmpty(userIdList)) {
            return;
        }
        //保存参数设置
        List<SysUserRole> roleUserList = Lists.newArrayList();
        //设置用户参数，并将参数对象保存到roleUserList
        for (Integer userId : userIdList) {
            SysUserRole roleUser = SysUserRole.builder().roleId(roleId).userId(userId).operator(RequestHolder.getCurrentUser().getUsername())
                    .operateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest())).operateTime(new Date()).build();
            roleUserList.add(roleUser);
        }
        //执行添加
        sysRoleUserMapper.batchInsert(roleUserList);
    }
    
    private void saveRoleUserLog(int roleId, List<Integer> before, List<Integer> after) {
        SysLogWithBLOBs sysLog = new SysLogWithBLOBs();
        sysLog.setType(LogType.TYPE_ROLE_USER);
        sysLog.setTargetId(roleId);
        sysLog.setOldValue(before == null ? "" : JsonMapper.objToString(before));
        sysLog.setNewValue(after == null ? "" : JsonMapper.objToString(after));
        sysLog.setOperator(RequestHolder.getCurrentUser().getUsername());
        sysLog.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysLog.setOperateTime(new Date());
        sysLog.setStatus(1);
        sysLogMapper.insertSelective(sysLog);
    }
}
